import sys
import math
import os
from helper import getFileName


def showHelp(isExit):
    helpInfo = """
  ：若已经定义别名：ptest='python phraseTest.py' 则用法如下：
  语法: ptest [num] [isLianXi]
  ptest # 显示帮助
  ptest 611 y # 练习6年级第1册第1单元
  ptest 611   # 测试6年级第1册第1单元
  """
    print(helpInfo)

    if isExit:
        sys.exit(1)


def getLines():
    fileName = getFileName(True)
    if not fileName:
        showHelp(True)
    fileName = r"E:\pythonLearn\phrase\%s" % fileName
    print("fileName", fileName)
    if not os.path.exists(fileName):
        print("file not found: %s" % fileName)
        sys.exit(1)

    lines = []

    def noMoreEmptyLine(lineTup):
        i, line = lineTup
        if line == "\n" and (i == 0 or i == len(lines) - 1 or lines[i + 1] == "\n"):
            return False
        return True

    with open(fileName, "r", encoding="utf8") as fp:
        lines = fp.readlines()
        # 过滤掉开始空行，末尾空行和连续空行
        linesFilter = filter(noMoreEmptyLine, enumerate(lines))
        linesMap = map(lambda t: t[1], list(linesFilter))
        lines = list(linesMap)

    return lines


def rmLineFeed(line):
    return line.replace("\n", "")


def getParts(lines):
    emptyLineIndexes = [index for index, line in enumerate(lines) if line == "\n"]
    parts = []
    start = 0
    while len(emptyLineIndexes) > 0:
        stop = emptyLineIndexes.pop(0)
        parts.append(lines[start:stop])
        start = stop + 1

    lastPart = lines[start:]
    parts.append(lastPart)

    for part in parts:
        for i, line in enumerate(part):
            part[i] = rmLineFeed(line)

    return parts


def toChunks(ls, size=2):
    count = math.ceil(len(ls) / size)
    start = 0
    chunks = []
    while count > 0:
        chunks.append(ls[start : start + size])
        count -= 1
        start += size

    return chunks


def parsePartToDict(part):
    phrase, meaning, dashLine, *examples = part
    examChunks = toChunks(examples, 2)
    examLs = [{"en": en, "cn": cn} for en, cn in examChunks]
    return {"phrase": phrase, "meaning": meaning, "examples": examLs}


def parseParts(parts):
    return [parsePartToDict(part) for part in parts]


if __name__ == "__main__":
    if len(sys.argv) < 2:
        showHelp(True)

    # print(getLines())
    parts = getParts(getLines())
    phraseList = parseParts(parts)
    print(phraseList)
